package com.jokerpan.project.controller;

import com.jokerpan.project.annotation.AccessLimit;
import com.jokerpan.project.commons.ActionResult;
import com.jokerpan.project.commons.ResultBuilder;
import com.jokerpan.project.entity.Users;
import com.jokerpan.project.util.UserTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("message")
@Api("消息操作Api")
public class MessageController {

    @Resource
    RedisTemplate redisTemplate;
    @Resource
    UserTool userTool;

    @GetMapping("/saveMsg")
    @AccessLimit(seconds = 6, maxCount = 5)
    @ApiOperation("保存消息")
    @PreAuthorize("hasPermission('','user:update')")
    public ActionResult saveMsg(String msg) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String name = msg.split("_")[0];
        String userMsg = "";
        String key = "";
        String type = msg.split("_")[1].split("-")[0];
        if (type.equals("message")){
            key = name + "_messageList";
        }else if(type.equals("notification")){
            key = name + "_notificationList";
        }
        if (redisTemplate.hasKey(key)){
            userMsg = operations.get(key);
            if (userMsg.lastIndexOf(",") == userMsg.length() - 1){
                userMsg = userMsg.substring(0,userMsg.length()-1);
            }
        }
        if (StringUtils.isBlank(userMsg)){
          userMsg += msg.split("_")[1] + ",";
        }else {
          userMsg += "," + msg.split("_")[1];
        }
        operations.set(key, userMsg, 24, TimeUnit.HOURS);
        return ResultBuilder.buildActionSuccess();
    }

    @GetMapping("/clearMsg")
    @AccessLimit(seconds = 6, maxCount = 5)
    @ApiOperation("清空消息")
    @PreAuthorize("hasPermission('','user:update')")
    public ActionResult clearMsg(@RequestParam("type") String type) {
        Users users = userTool.getCurrentUser();
        String key = users.getLoginName() + "_" + type;
        if (redisTemplate.hasKey(key)){
            redisTemplate.delete(key);
        }
        return ResultBuilder.buildActionSuccess();
    }
}
